RongIMClient.init("8w7jv4qb82s8y");//这是初始化，需要填参数就是你的APPKEY。这个不难理解。
var token = $.cookie('user_r_token');//注册时的token
//连接融云
RongIMClient.connect(token,
    {
        onSuccess: function(userId) {
            console.log("Login successfully." + userId);
            console.log(typeof $.cookie('old_room_id'),$.cookie('old_room_id'));
            if($.cookie('old_room_id')!=$.cookie('room_id')&&$.cookie('old_room_id')!=''&&typeof $.cookie('old_room_id')!='undefined'){
                var msg = new RongIMLib.TextMessage({
                    content:'自定义消息',
                    messageName:'TextMessage',
                    extra:'{"isForce":"false","isMoveIn":false,"isOwner":false,"moveInOut_head":"'+$.cookie("user_head")+'","moveInOut_nickName":"'+$.cookie("user_nickname")+'","moveInOut_uid":"'+$.cookie("user_id")+'","appendedSystemAlert":"'+$.cookie("user_nickname")+'离开聊天室","fromHead":"'+$.cookie("user_head")+'","fromNickName":"'+$.cookie("user_nickname")+'","shouldInsertToMessage":true,"shouldUpDateRoomInfo":true,"subType":"FTCustomMessageMoveInOrOutModel"}',
                    user:{
                        id:$.cookie('user_id'),
                        name:$.cookie('user_nickname'),
                        portrait:$.cookie('user_head'),
                    }
                });
                getMessageOldRoom(msg);
                $.cookie('old_room_id',$.cookie('room_id'),{path:'/'});
                RongIMClient.getInstance().quitChatRoom($.cookie('old_room_id'), {
                    onSuccess: function (){
                        RongIMClient.getInstance().joinChatRoom($.cookie('room_id'), -1, {
                            onSuccess: function() {
                                $('.chat-list').append('<p class="in_out">已进入关键词为：'+ $.cookie('room_keyword') +'的聊天室<p>');
                                var msg = new RongIMLib.TextMessage({
                                    content:'自定义消息',
                                    messageName:'TextMessage',
                                    extra:'{"isForce":"false","isMoveIn":true,"isOwner":false,"moveInOut_head":"'+$.cookie("user_head")+'","moveInOut_nickName":"'+$.cookie("user_nickname")+'","moveInOut_uid":"'+$.cookie("user_id")+'","appendedSystemAlert":"'+$.cookie("user_nickname")+'进入聊天室","fromHead":"'+$.cookie("user_head")+'","fromNickName":"'+$.cookie("user_nickname")+'","shouldInsertToMessage":true,"shouldUpDateRoomInfo":true,"subType":"FTCustomMessageMoveInOrOutModel"}',
                                    user:{
                                        id:$.cookie('user_id'),
                                        name:$.cookie('user_nickname'),
                                        portrait:$.cookie('user_head')
                                    }
                                });
                                getMessage(msg);
                            },
                            onError: function(error) {
                                // 加入聊天室失败
                            }
                        });
                    },
                    onError: function (error) {
                        // 退出聊天室失败。
                    }
                });
            }else{
                RongIMClient.getInstance().joinChatRoom($.cookie('room_id'), -1, {
                    onSuccess: function() {
                        $('.chat-list').append('<p class="in_out">已进入关键词为：'+ $.cookie('room_keyword') +'的聊天室<p>');
                        var msg = new RongIMLib.TextMessage({
                            content:'自定义消息',
                            messageName:'TextMessage',
                            extra:'{"isForce":"false","isMoveIn":true,"isOwner":false,"moveInOut_head":"'+$.cookie("user_head")+'","moveInOut_nickName":"'+$.cookie("user_nickname")+'","moveInOut_uid":"'+$.cookie("user_id")+'","appendedSystemAlert":"'+$.cookie("user_nickname")+'进入聊天室","fromHead":"'+$.cookie("user_head")+'","fromNickName":"'+$.cookie("user_nickname")+'","shouldInsertToMessage":true,"shouldUpDateRoomInfo":true,"subType":"FTCustomMessageMoveInOrOutModel"}',
                            user:{
                                id:$.cookie('user_id'),
                                name:$.cookie('user_nickname'),
                                portrait:$.cookie('user_head')
                            }
                        });
                        getMessage(msg);
                    },
                    onError: function(error) {
                        // 加入聊天室失败
                    }
                });
            }
        },
        onTokenIncorrect: function() {
            console.log('token无效');
        },
        onError:function(errorCode){
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = '未知错误';
                    break;
                case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
            }
            console.log(errorCode);
        }
    });

//设置连接监听状态
RongIMClient.setConnectionStatusListener({
    onChanged: function (status) {
        switch (status) {
            case RongIMLib.ConnectionStatus.CONNECTED:
                console.log('链接成功');
                break;
            case RongIMLib.ConnectionStatus.CONNECTING:
                console.log('正在链接');
                break;
            case RongIMLib.ConnectionStatus.DISCONNECTED:
                console.log('断开连接');
                break;
            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                $('.chat-list').html('<p style="text-align: center">'+'已进入其他聊天室，本聊天室已经退出'+'</p>');
                //退出聊天室
                console.log('其他设备登录');
                break;
            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                console.log('域名不正确');
                break;
            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                console.log('网络不可用');
                break;
        }
    }});
//判断消息类型

RongIMClient.setOnReceiveMessageListener({
    // 接收到的消息
    onReceived: function (message) {
        // 判断消息类型
        switch (message.messageType) {
            case RongIMClient.MessageType.TextMessage:
                console.log(message);
                if(typeof message.content.extra=='undefined'){
                    if(typeof message.content.extra == 'undefined'){
                        var txt = '<div class="message get">\n'+'<div class="message-img">\n'+'<small>'+message.content.user.name+'</small><img src="'+message.content.user.portrait+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' +message.content.content+'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
                        $('.chat-list').append(txt);
                        $('.chat-list').animate({scrollTop:$(document).height()},200);
                    }else{
                        var txt = '<div class="message get">\n'+'<div class="message-img">\n'+'<small>'+message.content.user.name+'</small><img src="'+message.content.user.portrait+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' + '<img src="bqb/'+ JSON.parse(message.content.extra).local_imageName +'.png" alt="">' +'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
                        $('.chat-list').append(txt);
                        $('.chat-list').animate({scrollTop:$(document).height()},200);
                    }
                }else{
                    var msg=message.content.extra;
                    var msg_type = JSON.parse(msg);
                    console.log(message);
                    //图片判断
                    if( msg_type.subType=='FTCustomMessageSendImageModel'){
                        var txt = '<div class="message get">\n'+'<div class="message-img">\n'+'<small>'+message.content.user.name+'</small><img src="'+message.content.user.portrait+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' +' <img src="bqb/'+msg_type.local_imageName+'.png"> '+'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
                        $('.chat-list').append(txt);
                        $('.chat-list').animate({scrollTop:$(document).height()},200);
                    }else if(msg_type.subType=='FTCustomMessageMoveInOrOutModel'){
                        //是否是进入或退出房间
                        var txt = '<p class="in_out">'+msg_type.appendedSystemAlert+'</p>'
                        $('.chat-list').append(txt);
                        $('.chat-list').animate({scrollTop:$(document).height()},200);
                        //    礼物消息
                    }else if(msg_type.subType=='FTCustomMessageGiftModel'){
                        var txt = '<p class="in_out">'+msg_type.appendedSystemAlert+'</p>'
                        $('.chat-list').append(txt);
                        $('.chat-list').animate({scrollTop:$(document).height()},200);
                    }else if(msg_type.subType=='FTCustomMessageSendVoiceModel'){
                        //语音消息
                        var txt = '<div class="message get">\n'+'<div class="message-img">\n'+'<img src="'+message.content.user.portrait+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' +'收到一条语音消息，请在手机上查看'+'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
                        $('.chat-list').append(txt);
                        $('.chat-list').animate({scrollTop:$(document).height()},200);
                    }else if(msg_type.subType=='FTCustomMessageSendRedEnvelopeModel'){
                        //    红包消息
                        var txt = '<div class="message get">\n'+'<div class="message-img">\n'+'<img src="'+message.content.user.portrait+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' +'我发了一个红包，请在手机上查看'+'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
                        $('.chat-list').append(txt);
                        $('.chat-list').animate({scrollTop:$(document).height()},200);
                    }else if(msg_type.subType=='FTCustomMessagePushModel'){
                       if(msg_type.isBeigin){
                          var txt = '<p class="in_out">主播开启了直播</p>';
                           $('.room-video').show();
                           $('.chat-list').append(txt);
                        }else{
                          var txt =  '<p class="in_out">主播结束了直播</p>';
                          $('.room-video').hide();
                           $('.chat-list').append(txt);
                       }

                    }

                }
                break;
            case RongIMClient.MessageType.ImageMessage:
                // 图片消息测试成功
                var txt = '<div class="message get">\n'+'<div class="message-img">\n'+'<small>'+message.content.user.nickname+'</small><img src="'+message.content.user.portrait+'" alt="">\n' +'</div>\n' +'<div class="message-content bigimgbox">\n' +'<img src="'+message.content.imageUri+'">'+'</div>\n' +'<div class="clearfix"></div>\n' +'</div>';
                $('.chat-list').append(txt);
                $('.chat-list').animate({scrollTop:$(document).height()},200);
                break;
            //    语音消息
            case RongIMClient.MessageType.FTCustomMessageModel:

                break;
            //位置信息(地图)
            case RongIMClient.MessageType.FTCustomMessageModel:
                // do something...
                break;
            //   图文信息
            case RongIMClient.MessageType.RichContentMessage:
                // do something...
                break;
            case RongIMClient.MessageType.DiscussionNotificationMessage:
                // do something...
                break;
            case RongIMClient.MessageType.InformationNotificationMessage:
                // do something...
                break;
            //    断网重连
            case RongIMClient.MessageType.ContactNotificationMessage:
                // do something...
                break;
            case RongIMClient.MessageType.ProfileNotificationMessage:
                // do something...
                break;
            case RongIMClient.MessageType.CommandNotificationMessage:
                // do something...
                break;
            case RongIMClient.MessageType.CommandMessage:
                // do something...
                break;
            case RongIMClient.MessageType.UnknownMessage:
                // do something...
                break;
            default:
            // 自定义消息
        }
    }
});


function getMessageOldRoom(messages){
    //生成聊天内容
    //在页面追加你要生成的内容
    // 定义消息类型,文字消息使用 RongIMLib.TextMessage
    var conversationtype = RongIMLib.ConversationType.CHATROOM; // 聊天室
    var targetId = $.cookie('old_room_id')||''; // 目标 Id
    RongIMClient.getInstance().sendMessage(conversationtype, targetId, messages, {
            // 发送消息成功
            onSuccess: function (message) {
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                console.log("Send successfully");

            },
            onError: function (errorCode, message) {
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    default :
                        info = "x";
                        break;
                }
                console.log('发送失败:' + info);
            }
        }
    );
}

function getMessage(messages){
    //生成聊天内容
    //在页面追加你要生成的内容
    // 定义消息类型,文字消息使用 RongIMLib.TextMessage
    var conversationtype = RongIMLib.ConversationType.CHATROOM; // 聊天室
    var targetId = $.cookie('room_id'); // 目标 Id

    RongIMClient.getInstance().sendMessage(conversationtype, targetId, messages, {
            // 发送消息成功
            onSuccess: function (message) {
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                console.log("Send successfully");

            },
            onError: function (errorCode, message) {
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    default :
                        info = "x";
                        break;
                }
                console.log('发送失败:' + info);
            }
        }
    );
}
//回车发送消息
$('.text-input').keyup(function(eventTag){
    var event=eventTag||windows.event;
    var e=event.srcElement||event.target;
    if(event.keyCode ==13&&$('.text-input').val()!=''){

        var msg = new RongIMLib.TextMessage({
            content:$('.text-input').val(),
            messageName:'TextMessage',
            user:{
                id:$.cookie('user_id'),
                name:$.cookie('user_nickname'),
                portrait:$.cookie('user_head')
            }
        });
        getMessage(msg);
        var txt = '<div class="message send">\n'+'<div class="message-img">\n'+'<img src="'+$.cookie('user_head')+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' +$('.text-input').val()+'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
        $('.chat-list').append(txt);
        $('.chat-list').animate({scrollTop:$(document).height()},200);
        $('.text-input').val('');
    }
});
// 发送emoji表情包
$('a.fasong').click(function(){
    if($('.text-input').val()!=''){
        var msg = new RongIMLib.TextMessage({
            content:$('.text-input').val(),
            messageName:'TextMessage',
            user:{
                id:$.cookie('user_id'),
                name:$.cookie('user_nickname'),
                portrait:$.cookie('user_head')
            }
        });
        getMessage(msg);
        var txt = '<div class="message send">\n'+'<div class="message-img">\n'+'<img src="'+$.cookie('user_head')+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' +$('.text-input').val()+'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
        $('.chat-list').append(txt);
        $('.chat-list').animate({scrollTop:$(document).height()},200);
        $('.text-input').val('');
    }else{
        return false;
    }

});
//发送亿信表情包
$(document).on('click','.yxbqb',function(){
    var msg = new RongIMLib.TextMessage({
        content:"自定义消息",
        extra:"{'emojiIndex':"+$(this).data('id')+",'isEmoji':'true','local_imageName':"+$(this).data('name')+",'shouldInsertToMessage':'true','shouldUpDateRoomInfo':'false','subType':'FTCustomMessageSendImageModel'}",
        imageUri:'',
        messageName:'TextMessage',
        user:{
            id:$.cookie('user_id'),
            name:$.cookie('user_nickname'),
            portrait:$.cookie('user_head')
        }
    });
    getMessage(msg);
    var txt = '<div class="message send">\n'+'<div class="message-img">\n'+'<img src="'+$.cookie('user_head')+'" alt="">\n' +'</div>\n' +'<div class="message-content">\n' + '<img src="bqb/'+ $(this).data('name') +'.png" alt="">' +'</div>\n' +'<div class="clearfix"></div>\n' +'</div>'
    $('.chat-list').append(txt);
    $('.chat-list').animate({scrollTop:$(document).height()},200);

});
//图片上传
(function(){
    var inputFile = $('.text-input');
    var msg = $('#fsimg');
    var uploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4',    //上传模式,依次退化
        browse_button: 'fsimg',       //上传选择的点选按钮，**必需**
        //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        //uptoken : 'xxxxxxxxxxxxxx',
        uptoken: $.cookie('qtoken'),
        save_key: true,        // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
        domain: $.cookie('qdm')+'/',
        // container: 'container',//上传区域DOM ID，默认是browser_button的父元素，
        max_file_size: '1000mb',           //最大文件体积限制
        flash_swf_url: 'js/Moxie.swf',  //引入flash,相对路径
        max_retries: 0,                   //上传失败最大重试次数
        dragdrop: true,                   //开启可拖曳上传
        // drop_element: 'chat-list',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '4mb',                //分块上传时，每片的体积
        auto_start: true,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
        filters: {  //对上传文件类型进行限制
            mime_types : [
                { title : "Image files", extensions : "jpg,gif,png"}
            ],
            max_file_size: "4mb",
            prevent_duplicates: true
        },
        init: {
            'FilesAdded': function (up, files) {
                plupload.each(files, function (file) {
                    // 文件添加进队列后,处理相关的事情
                    msg.append(' FilesAdded 事件（文件添加进队列后,处理相关的事情）<br />');
                });
            },
            'BeforeUpload': function (up, file) {
                // 每个文件上传前,处理相关的事情
                msg.append(' BeforeUpload 事件（每个文件上传前,处理相关的事情）<br />');
            },
            'UploadProgress': function (up, file) {
                // 每个文件上传时,处理相关的事情
                var percent = Math.round(file.loaded / file.size * 100);
                msg.append(' UploadProgress 事件（每个文件上传时,处理相关的事情），已上传：' + percent + '%<br />');
            },
            'FileUploaded': function (up, file, info) {
                // 每个文件上传成功后,处理相关的事情
                // 其中 info 是文件上传成功后，服务端返回的json，形式如
                // {
                //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //    "key": "gogopher.jpg"
                //  }
                // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
                var domain = up.getOption('domain');
                var res = JSON.parse(info);
                var sourceLink = domain + res.key; //获取上传成功后的文件的Url
                var msgsend = '<div class="message send">\n' +
                                '<div class="message-img">\n' +
                                '<img src="http://pbqt8ydnc.bkt.clouddn.com/80880201808291459327639.png" alt="">\n' +
                                '</div>\n' +
                                '<div class="message-content">\n' +
                                '<img src="'+sourceLink+'" alt=""></div>\n' +
                                '<div class="clearfix"></div>\n' +
                                '</div>';
                $('.chat-list').append(msgsend);
                var msg = new RongIMLib.ImageMessage({
                    // content
                    imageUri:sourceLink,
                    messageName:'ImageMessage',
                    user:{
                        id:$.cookie('user_id'),
                        name:$.cookie('user_nickname'),
                        portrait:$.cookie('user_head')
                    }
                });
                getMessage(msg);
            },
            'Error': function (up, err, errTip) {
                //上传出错时,处理相关的事情<br>
                msg.append(' Error 事件（上传出错时,处理相关的事情）<br />');
            },
            'UploadComplete': function () {
                //队列文件处理完毕后,处理相关的事情
                msg.append(' UploadComplete 事件（队列文件处理完毕后,处理相关的事情）<br />');
            },
            'Key': function (up, file) {
                // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
                // 该配置必须要在 unique_names: false , save_key: false 时才生效
                var key = "";
                // do something with key here
                return key
            }
        }
    });
})();